//
//  LoginView.swift
//  FuXingApp
//
//  Created by zqw on 2021/8/2.
//

import UIKit
import ActiveLabel
import SwiftyJSON

typealias loginActionClosure = (_ type: Int,_ params: LoginRequest) -> ()

class LoginView: UIView, UITextFieldDelegate {
    var txtIndex:Int = 0
    var actionClosure :loginActionClosure?
    private var timer: Timer?
    
    
    //MARK: -init
    init(_ type: loginViewType, frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        timer?.invalidate()
        timer = nil
        kNotifiDefault.removeObserver(self)
    }
    
    // MARK: handle event
    ///事件
    /// 倒计时
    private var isCounting: Bool = false {
        willSet(newValue) {
            if newValue {
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer(timer:)), userInfo: nil, repeats: true)
            }else{
                timer?.invalidate()
                timer = nil
            }
        }
    }
    /// 当前剩余秒数
    private var remainingSeconds: Int = 0 {
        willSet(newSeconds) {
            let seconds = newSeconds % 60
            fetchCodeBtn.setTitle("重新获取(\(seconds)s)", for: .normal)
            if seconds <= 0 {
                self.fetchCodeBtn.setTitle("重新获取", for: .normal)
                self.fetchCodeBtn.isUserInteractionEnabled = true
            }
        }
    }
 
    
    // MARK: - UI
    func setup() {
        self.addSubview(titleLabel)
        self.addSubview(phonesubLabel)
        self.addSubview(phoneTField)
        self.addSubview(msgCodeTField)
        self.addSubview(fetchCodeBtn)
        self.addSubview(subTitleLabel)
        self.addSubview(loginBtn)

        self.addSubview(privacyBtn)
        self.addSubview(privacyLbl)
        
        /// Layout
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().offset(40)
            make.top.equalToSuperview().offset(143)
        }
        
        phonesubLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.left)
            make.top.equalTo(titleLabel.snp.bottom).offset(17+10)
        }
        phoneTField.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(40)
            make.left.equalTo(phonesubLabel.snp.right).offset(12)
            make.top.equalTo(titleLabel.snp.bottom).offset(17)
            make.height.equalTo(44)
        }
        let line = UIView()
        line.backgroundColor = UIColor.init(hex: "#000000")?.withAlphaComponent(0.1)
        self.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalTo(phonesubLabel.snp.left)
            make.top.equalTo(phoneTField.snp.bottom).offset(-1)
            make.height.equalTo(1)
            make.width.equalTo(38)
        }
        msgCodeTField.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.left)
            make.top.equalTo(phoneTField.snp.bottom).offset(15)
            make.right.equalToSuperview().inset(40)
            make.height.equalTo(44)
        }
        fetchCodeBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(40)
            make.centerY.equalTo(msgCodeTField.snp.centerY)
        }
        subTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.left)
            make.top.equalTo(msgCodeTField.snp.bottom).offset(6)
        }
        
        loginBtn.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(32)
            make.top.equalTo(subTitleLabel.snp.bottom).offset(48)
            make.height.equalTo(48)
        }
        // bottom
        privacyBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-BottomHomeHeight-23)
            make.size.equalTo(22)
        }
        privacyLbl.snp.makeConstraints { make in
            make.left.equalTo(self.privacyBtn.snp.right).offset(0)
            make.centerY.equalTo(self.privacyBtn)
            make.right.equalToSuperview().inset(0)
        }
        
    }
    
    // MARK: - lazy
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.pfmFont(ofSize: 28)
        label.numberOfLines = 0
        label.text = "欢迎登录拾洁清洁"
        label.textColor = .appTextColor
        label.textAlignment = .left; return label
    }()
    ///懒加载subTitle
    private lazy var subTitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.pfrFont(ofSize: 12)
        label.numberOfLines = 0
        label.text = "未注册手机号登录后将自动注册"
        label.textColor = UIColor.init(hex: "#000000")?.withAlphaComponent(0.4)
        label.textAlignment = .left;return label
    }()
    private lazy var phonesubLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.pfrFont(ofSize: 16)
        label.frame.size = CGSize(width: 29, height: 22)
        label.text = "+61"
        label.textColor = UIColor.init(hex: "#3D3D3D")?.withAlphaComponent(0.4)
        label.textAlignment = .left;return label
    }()
    /// 账号
    fileprivate lazy var phoneTField: UnderLineTextField = {
        let tf = UnderLineTextField()
        tf.clearButtonMode = .always
        tf.backgroundColor = .white
        tf.keyboardType = .numberPad
        tf.returnKeyType = .done
        tf.delegate = self
        tf.addTarget(self, action: #selector(textFieldDidEndEditing), for: .editingChanged)
        tf.textFieldInit(limitLength: 10, holder: "请输入手机号")//手机号需要间隔，正常:11
        return tf
    }()
    /// 验证码
    fileprivate lazy var msgCodeTField: UnderLineTextField = {
        let tf = UnderLineTextField()
        tf.backgroundColor = .white
        tf.returnKeyType = .done
        tf.delegate = self
        tf.keyboardType = .numberPad
        tf.textFieldInit(limitLength: 6, holder: "请输入验证码")
        if #available(iOS 12.0, *) {
            tf.textContentType = .oneTimeCode
        }
        tf.addTarget(self, action: #selector(textFieldDidEndEditing), for: .editingChanged)
        return tf
    }()
   
    ///获取验证码
    private lazy var fetchCodeBtn: UIButton = {
        let button = UIButton()
        button.setTitle("获取验证码", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        button.setTitleColor(UIColor.init(hex: "#000000"), for: .normal)
        button.addTarget(self, action:#selector(btnTapped(_:)), for:.touchUpInside)
        button.tag = LoginActionType.fecthCode.rawValue
        button.sizeToFit()
        return button
    }()
    private lazy var loginBtn: UIButton = {
        let button = UIButton()
        button.setTitle("立即登录", for: .normal)
        button.titleLabel?.font = UIFont.pfmFont(ofSize: 18)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action:#selector(btnTapped(_:)), for:.touchUpInside)
        button.tag = LoginActionType.loginNormal.rawValue
        button.backgroundColor = UIColor.init(hex: "#C7C9CE")
        button.layer.cornerRadius = 24
        button.layer.masksToBounds = true
        return button
    }()

    
    /// 底部登录方式和协议
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    private lazy var privacyBtn: UIButton = {
        let button = UIButton()
        button.setImage(UIImage.init(named: "icon_normal_circle"), for: .normal)
        button.setImage(UIImage.init(named: "icon_selected_circle"), for: .selected)
        button.addTarget(self, action:#selector(btnTapped(_:)), for:.touchUpInside)
        button.tag = LoginActionType.loginPrivacy.rawValue
        return button
    }()
    ///协议
    private lazy var privacyLbl: ActiveLabel = {
        let label = ActiveLabel()
        let customType = ActiveType.custom(pattern: "《拾舍清洁平台服务协议》")
        let customType1 = ActiveType.custom(pattern: "《隐私政策》")
        label.enabledTypes = [customType , customType1]
        label.text = "登录即视为同意《拾舍清洁平台服务协议》、《隐私政策》"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor.init(hex: "#3D3D3D")
        label.textAlignment = .left
        label.handleCustomTap(for: customType) { customType in
            let vc = SSPolicyViewController()
            vc.type = 1
            UIViewController.current().navigationController?.pushViewController(vc, animated: true)
        }
        label.handleCustomTap(for: customType1) { customType1 in
            let vc = SSPolicyViewController()
            vc.type = 0
            UIViewController.current().navigationController?.pushViewController(vc, animated: true)
        }
        label.customColor[customType] = UIColor.init(hex: "#4DAAF8")
        label.customColor[customType1] = UIColor.init(hex: "#4DAAF8")
        return label
    }()
 
    
    ///数据
    private lazy var reqLogin: LoginRequestModel = {
        let req = LoginRequestModel()
        return req
    }()
}

/// 键盘遮挡和输入
extension LoginView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        if self.frame.origin.y < 0 {
            UIView.animate(withDuration: 0.4, animations: {
                self.frame.origin.y = 0
                self.endEditing(true)
            })
        }
    }
    
    @objc func textFieldDidBeginEditing(_ textField: UITextField) {
        //view弹起跟随键盘，高可根据自己定义
        UIView.animate(withDuration: 0.4, animations: {
            self.frame.origin.y = -40
        })
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.returnKeyType == .done {
            UIView.animate(withDuration: 0.4, animations: {
                self.frame.origin.y = 0
                textField.resignFirstResponder()
            })
            return true
        }
        return false
    }
    
}
// MARK: - 验证码倒计时
extension LoginView {
    @objc func updateTimer(timer: Timer) {
        //启动倒计时
        if remainingSeconds > 0 {
            remainingSeconds -= 1
            self.fetchCodeBtn.isUserInteractionEnabled = false
        }else{
            self.fetchCodeBtn.setTitle("重新获取", for: .normal)
            self.fetchCodeBtn.isUserInteractionEnabled = true
            isCounting = !isCounting
            timer.invalidate()
        }
        
    }
}

/// 文本输入按钮状态改变
extension LoginView {
    @objc func textFieldDidEndEditing(_ textField: UITextField) {
       if textField == phoneTField || textField == msgCodeTField {
           let b = (phoneTField.text!.count >= 9 && msgCodeTField.text!.count >= 6)
           setupLoginBtnStatus(b)
        }
        
    }
    fileprivate func setupLoginBtnStatus(_ isEnable: Bool) {
        loginBtn.setTitleColor(isEnable ? .white : .white, for: .normal)
        loginBtn.backgroundColor = UIColor.init(hex: isEnable ? "#4DAAF8" : "#C7C9CE")
        loginBtn.isUserInteractionEnabled = isEnable
    }
}


/// 按钮点击事件
extension LoginView {
    // MARK: - btnAction
    @objc func btnTapped(_ button:UIButton){
        switch button.tag {
            // 登录
        case LoginActionType.loginNormal.rawValue:
            if checkLoginStep() {
                let pardDic = reqLogin.req
                if actionClosure != nil {
                    actionClosure!(button.tag, pardDic)
                }
            }
            // 协议
        case LoginActionType.loginPrivacy.rawValue:
            button.isSelected = !button.isSelected
            // 获取验证码
        case LoginActionType.fecthCode.rawValue:
            if checkPhone(isShow: true) {
                //network
                fecthMsgcode(reqLogin.req.phoneNum)
            }
        default: break
            
        }
        
    }
    
    // 手机号逻辑
    func checkPhone(isShow: Bool) -> Bool {
        let phone = phoneTField.text!
        // 校验手机号
        if phone.isEmpty {
            if isShow {
                self.makeToast("手机号不能为空！")
            }
            return false
        }
//        if(phone.count != 9){
//            self.makeToast("请输入正确的手机号！")
//            return false
//        }
        reqLogin.req.phoneNum = phone
        return true
    }
    
    // 登录逻辑
    func checkLoginStep() -> Bool {
        let msgCode = msgCodeTField.text!
        // 校验手机号
        if !checkPhone(isShow: true) {
            return false
        }
        // 校验验证码
        if msgCode.isEmpty {
            self.makeToast("验证码不能为空！")
            return false
        }
        reqLogin.req.msgCodeNum = msgCode
        
        if !bottomView.isHidden {
            //登录的时候需要勾选协议
            if !privacyBtn.isSelected {
                makeToast("请先阅读并勾选相关条款内容")
                self.endEditing(true)
                return false
            }
        }
        return true
    }
    
}
// 网络加载
extension LoginView {
    func fecthMsgcode(_ phone: String){
        let param = [
            "phoneNo": reqLogin.req.phoneNum,
                ] as [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.sendMsg_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["data"].stringValue
                let data = json["retMsg"].stringValue
                if(retCode == "0000"){
                    self.remainingSeconds = 59
                    self.isCounting = true
                    dissmissToTast(msg: "验证码已发送！")
                }else{
                    dissmissToTast(msg: "\(data)")
                }

            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    dissmissToTast(msg: "\(message)")
//                }
            }
        }
        
    }
}

func dissmissToTast(msg:String) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        UIViewController.current().view.makeToast(msg)
    }
}

func dissmissToEscaping(finished: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        finished()
//        UIViewController.current().view.makeToast(msg)
    }
}



